<!--
 * @Description: 
 * @Author: Devin
 * @Date: 2021-11-10 10:45:27
 * @LastEditTime: 2021-11-11 14:45:54
 * @LastEditors: Devin
 * @Reference: 
-->
<template>
  <el-breadcrumb separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in breadcrumbLists" :key="item.path">
        <span v-if="index == breadcrumbLists.length - 1" class="no-redirect">{{
          item.meta.title
        }}</span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, watch, ref } from '@vue/runtime-core';
import { useRoute, useRouter } from 'vue-router';
export default defineComponent({
  name: '',
  components: {},
  setup() {
    const state: {
      breadcrumbLists: { path: ''; meta: { title: '' }; redirect: '' }[];
    } = reactive({
      breadcrumbLists: []
    });
    const route = ref(useRoute());
    const router = useRouter();

    /**
     * @description 判断是否为首页，如果不是这添加首页的路径
     * @param  {*}
     * @return {*}
     */
    const isHome = (route: { name: '' }): boolean => {
      const name: string | object = route && route.name;
      if (!name) {
        return false;
      }
      return name.trim().toLocaleLowerCase() === 'HomeIndex'.toLocaleLowerCase();
    };
    const getBreadcrumb = () => {
      // 获取当前路由的所有嵌套路径片段的路由记录
      let matched: any = route.value.matched.filter((item) => item.meta && item.meta.title);
      // 获取片段的第一个，用于后续操作
      const first: any = matched[0];
      // 判断是否为首页，如果不是则添加首页的路径
      if (!isHome(first)) {
        matched.unshift({ path: '/home/index', meta: { title: '首页' } });
      }
      state.breadcrumbLists = matched;
    };
    const handleLink = (item: { redirect: any; path: any }) => {
      const { redirect, path } = item;
      // 如果有重定向则会跳到重定向的地址中去
      if (redirect) {
        router.push(redirect);
        return;
      }
      router.push(path);
    };

    getBreadcrumb();

    watch(
      route,
      () => {
        // 如果是重定向则不需要刷新面包屑
        if (route.value.path.startsWith('/redirect/')) {
          return;
        }
        getBreadcrumb();
      },
      { deep: true }
    );

    return { ...toRefs(state), handleLink };
  }
});
</script>
<style scoped lang="scss">
/* breadcrumb transition */
.breadcrumb-enter-active,
.breadcrumb-leave-active {
  transition: all 0.5s;
}

.breadcrumb-enter,
.breadcrumb-leave-active {
  opacity: 0;
  transform: translateX(20px);
}

.breadcrumb-move {
  transition: all 0.5s;
}

.breadcrumb-leave-active {
  position: absolute;
}
</style>
